#!/bin/bash
########################################################################
# script name:  transport_restore.sh
# Used for:
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2012/03/14    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -m               Module (BW, EP, ERP, etc)
   -i               Index (ex.; 900045)

Ex.:
$0 -m BW -i 900045
$0 -m BW -i 90004
STOP
}
#######################################
# Get parameters
#######################################
while getopts m:i: OPTION
do
        case $OPTION in
        m)
                MODULES=$(echo $OPTARG | tr '[a-z]' '[A-Z]' | sed 's/,/ /g')
                ;;
        i)
                ID=$OPTARG
                ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
#if [ -z "$MODULES" ]; then usage; exit 1; fi
if [ -z "$ID" ]; then usage; exit 1; fi
if [ "$(whoami)" != "root" ]; then echo "You need to be root (try with sudo)"; exit 1; fi
#######################################
# Variables and environnement
#######################################
SSH_OPTS="-x -o ConnectTimeout=5 -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=quiet"
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
REMOTE=sapsmp-nfs
BASEDIR=/usr/sap/trans_exp
SUBDIR=( data cofiles log )
#######################################
echo -e "Getting list of modules: \c "
for i in ${SUBDIR[@]}; do DIRLIST[${#DIRLIST[@]}]="$BASEDIR/\*/$i/retention"; done
MODULESLIST=$(echo "for i in ${DIRLIST[@]}; do find \$i; done | awk -F'/' '{print \$5}'|sort|uniq|xargs" | sudo -u saunix ssh $SSH_OPTS $REMOTE "cat | sudo bash")
echo $MODULESLIST
if [ ! -z $MODULES ]
then
	if [ "$(echo $MODULESLIST | tr ' ' '\n' | \grep -w $MODULES | tail -n 1)" != "$MODULES" ]
	then
		echo -e "No module of that name ($MODULES)"
		exit
	else
		MODULESLIST=$MODULES
	fi
fi
#######################################
X=( `echo $MODULESLIST` )
if [ ${#X[@]} = 1 ]; then X=$MODULESLIST; else X="{$(echo ${X[@]}|tr ' ' ',')}"; fi
Y="{$(echo ${SUBDIR[@]} | tr ' ' ',')}"
COMMAND="(find /usr/sap/trans_exp/$X/$Y/retention -name '*.summary' -exec grep -q $ID {} \;  -ls 2> /dev/null)| awk '{print \$NF}'"
FILES=$(echo $COMMAND | sudo -u saunix ssh $SSH_OPTS $REMOTE "cat | sudo bash")
#######################################
# MAIN
#######################################
echo -e "Populating file array with index(es) \c "
x=1
for i in $FILES
do
	COMMAND="grep $ID $i | awk '{print \$NF}'"
	GREP=$(echo $COMMAND | sudo -u saunix ssh $SSH_OPTS $REMOTE "cat | sudo bash")	
	for j in $GREP
	do
		i=$(echo $i | sed 's/summary/tar.gz/')
		FILE_a[$x]=$j:$i
		echo -e ".\c"
		((x++))
	done
done
echo done
echo "Found ${#FILE_a[@]} occurence(s)"
function play_array {
	x=1
	while [ $x -le ${#FILE_a[@]} ]
	do
		i=${FILE_a[$x]}
		echo "  $x) `echo $i|cut -d: -f1` in `echo $i|cut -d: -f2`"
		((x++))
	done
	echo
	if [ ${#FILE_a[@]} -gt 0 ]; then read -p "Enter the number corresponding to the file: "; else echo No files found with $ID, exiting; exit 1; fi
	if [ "$REPLY" -gt "${#FILE_a[@]}" ]; then echo; read -p "Please enter a number between 1 and ${#FILE_a[@]}: "; fi
	if [ "$REPLY" -gt "${#FILE_a[@]}" ]; then echo; echo "You're to dumb, exiting"; exit 1; fi
	FILE=${FILE_a[$REPLY]}
}
a1=n
while [ "$a1" != "y" ]
do
	echo
	play_array
	echo
	ID=$(echo $FILE|cut -d: -f1)
	FILEGZ=$(echo $FILE|cut -d: -f2)
	read -p "Selected to restore $ID from $(echo $FILEGZ | awk -F'/' '{print $NF}') [y/n]? " -e a1
done
echo
echo Restoring $ID from $FILEGZ
cat <<-'EOF' | sudo -u saunix ssh $SSH_OPTS $REMOTE "cat | sudo env ID=$ID FILEGZ=$FILEGZ bash"
	TARGET=$(cd `dirname $FILEGZ`; cd ..; pwd)
	if [ -f $TARGET/$ID ]; then echo; echo File $TARGET/$ID already exist, exiting; exit 1; fi
	gtar zx -C $TARGET -f $FILEGZ $ID && echo && echo File restored to $TARGET/$ID && echo
EOF
#######################################
exit 0
